<?php
namespace Reezy\APIToken;


use function base64_decode;
use function base64_encode;
use function base_convert;
use function explode;
use function hash_hmac;
use function join;
use function json_decode;
use function json_encode;
use function trim;

class APITokenUtil
{

    public static function encode(string $name, int $id, int $ts, string $payload, string $secretKey): string
    {
        $sig = self::hmac($name, $id, $ts, $payload, $secretKey);
        return trim(base64_encode(join('/', [$name, $id, $ts, $sig])), "=");
    }

    public static function decode(string $token): ?APITokenInfo
    {
        try {
            [$name, $id, $ts, $sig] = explode('/', base64_decode($token));

            if ($id > 0 && $ts > 0 && !empty($sig) && !empty($name)) {
                return new APITokenInfo($token, $name, $id, $ts, $sig);
            }
        } catch (\Exception $ex) {
        }
        return null;
    }

    public static function hmac(string $name, int $id, int $ts, string $payload, string $secretKey)
    {
        return base_convert(hash_hmac('sha256', join('/', [$name, $id, $ts, $payload]), $secretKey), 16, 36);
    }

}